<template>
  <van-empty v-if="showEmpty" description="暂无内容">
    <template #description>
      <span v-if="getToken()" style="color: #909399"
        >您没有被授权学习任何课程</span
      >
      <to-login v-else icon="home-o" text="请先登录" path="/login" />
    </template>
  </van-empty>
  <div v-else class="courses-container">
    <div ref="my_breadCrumb" class="breadcrumb">
      <span>所选课程：</span>
      <template v-for="(item, index) in breadcrumbs" :key="index">
        <span class="breadcrumb-item" @click="handleBreadcrumbClick(index)">{{
          item.name
        }}</span>
        <span v-if="index < breadcrumbs.length - 1" class="separator">/</span>
      </template>
    </div>
    <div class="divider" />

    <!-- 卡片列表 -->
    <van-pull-refresh
      v-if="table.length > 0"
      v-model="loading"
      @refresh="onRefresh"
      class="card-list"
    >
      <van-list
        v-model:loading="isLoading"
        :finished="finished"
        :finished-text="text"
        @load="onLoadMore"
      >
        <div class="card-wrapper" v-for="item in table" :key="item.id">
          <van-card
            :title="item.name"
            :desc="item.description"
            :thumb="item.cover"
            class="subject-card"
          >
            <template #footer>
              <div class="card-footer">
                <span>时长: {{ item.duration }}分钟</span>
                <van-button
                  @click="handleStart(item)"
                  type="primary"
                  size="small"
                  >开始学习</van-button
                >
              </div>
            </template>
          </van-card>
        </div>
      </van-list>
    </van-pull-refresh>

    <!-- 空状态显示 -->
    <TrainingDetail v-else :showTrainingDetail="showTrainingDetail" />
  </div>
</template>

<script setup>
import TrainingDetail from "@/components/trainingDetail.vue";
import { ref, onMounted, watch, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
import subjectApi from "@/api/subject/index";
import { getToken } from "@/utils/auth"; // get token from cookie
import ToLogin from "@/components/toLogin.vue";
import { showToast } from "vant";

const router = useRouter();
const route = useRoute();
const store = useStore();
const my_breadCrumb = ref(null);
const showTrainingDetail = ref({});
const showEmpty = ref(false);
import host from "@/utils/host";

const text = ref("没有更多了");
const loading = ref(false);
const onRefresh = () => {
  setTimeout(() => {
    showToast("刷新成功");
    loading.value = false;
    // 重置分页并重新加载数据
    currentPage.value = 1;
    table.value = [];
    loadData();
  }, 1000);
};

const currentPage = ref(1);
const pageSize = ref(5);
const finished = ref(false);
const isLoading = ref(false);

const table = ref([]);
// 使用 computed 从 Vuex 获取 breadcrumbs
const breadcrumbs = computed(() => store.getters.breadcrumbs);

// 加载数据的通用函数
const loadData = async (id = null, isLoadMore = false) => {
  if (!isLoadMore) {
    currentPage.value = 1;
    table.value = [];
    finished.value = false;
  }

  isLoading.value = true;
  try {
    let targetId = id;
    if (targetId === null && breadcrumbs.value.length > 0) {
      const lastBreadcrumb = breadcrumbs.value[breadcrumbs.value.length - 1];
      targetId = lastBreadcrumb.id;
    }

    if (targetId === null) {
      const res = await subjectApi.getMySubjects();
      if (res.data.length === 0) {
        showEmpty.value = true;
      } else {
        text.value = "";
        showEmpty.value = false;
        if (isLoadMore) {
          table.value = [...table.value, ...res.data];
        } else {
          table.value = res.data;
        }
      }
      // 根目录数据一次性加载完毕
      finished.value = true;
    } else {
      const res = await subjectApi.getByParentId(
        targetId,
        currentPage.value,
        pageSize.value
      );

      text.value = "没有更多了";
      if (res.data.records.length === 0 && currentPage.value === 1) {
        // 如果是第一页且没有数据，尝试获取详情
        const detailRes = await subjectApi.getSubjectMapById(targetId);
        showTrainingDetail.value = detailRes.data;
        console.log(showTrainingDetail)
        table.value = [];
      } else {
        // 追加数据
        if (isLoadMore) {
          table.value = [...table.value, ...res.data.records];
        } else {
          table.value = res.data.records;
        }
        // 判断是否已加载完所有数据
        finished.value = res.data.records.length < pageSize.value;
      }
    }

    // 确保在数据加载完成后，如果数据不足一页也标记为完成
    if (table.value.length > 0 && table.value.length < pageSize.value) {
      finished.value = true;
    }
  } catch (error) {
    console.error("加载数据失败:", error);
    showToast("加载失败，请重试");
  } finally {
    isLoading.value = false;
  }
};

// 加载更多数据
const onLoadMore = () => {
  if (finished.value) return;
  currentPage.value += 1;
  loadData(null, true);
};

const handleStart = async (item) => {
  const newBreadcrumbs = [
    ...breadcrumbs.value,
    { name: item.name, id: item.id },
  ];
  store.dispatch("learn/setBreadcrumbs", newBreadcrumbs);
  await loadData(item.id);
  updateRoute();
};

const handleBreadcrumbClick = async (index) => {
  if (index === breadcrumbs.value.length - 1) return;

  const newBreadcrumbs = breadcrumbs.value.slice(0, index + 1);
  store.dispatch("learn/setBreadcrumbs", newBreadcrumbs);

  const currentItem = breadcrumbs.value[index];
  await loadData(currentItem.id);
  updateRoute();
};

// 更新路由参数
const updateRoute = () => {
  // 跳过第一个"全部课程"项
  const pathArr = breadcrumbs.value.slice(1);
  const path = pathArr.map((item) => item.id).join(",");
  const names = pathArr.map((item) => encodeURIComponent(item.name)).join(",");

  router.replace({
    query: {
      ...route.query,
      path: path || "null",
      names: names || "全部课程",
    },
  });
};


// 监听路由变化
watch(
  () => route.query,
  () => {
    initFromRoute();
  }
);

onMounted(async () => {
  if (getToken()) {
    await initFromRoute();
  } else {
    showEmpty.value = true;
  }
});

const initFromRoute = async () => {
  // 检查是否需要重置面包屑
  if (route.query.resetBreadcrumbs === "true") {
    store.dispatch("learn/setBreadcrumbs", [{ name: "全部课程", id: null }]);
    await loadData(null);
    // 清除重置参数
    router.replace({
      query: {},
    });
    return;
  }

  // 如果有路由参数，优先使用路由参数
  const { path = "", names = "" } = route.query;
  if (path && names) {
    const pathArr = path.split(",");
    const nameArr = names.split(",");

    const newBreadcrumbs = [{ name: "全部课程", id: null }];

    // 重建面包屑路径
    for (let i = 0; i < pathArr.length; i++) {
      if (pathArr[i] !== "null") {
        newBreadcrumbs.push({
          id: Number(pathArr[i]),
          name: decodeURIComponent(nameArr[i]),
        });

        // 获取最后一级的数据
        if (i === pathArr.length - 1) {
          store.dispatch("learn/setBreadcrumbs", newBreadcrumbs);
          await loadData(Number(pathArr[i]));
          return;
        }
      }
    }
  }
  // 如果没有路由参数但有保存的breadcrumbs状态，使用最后一级的id获取数据
  else if (store.getters.breadcrumbs.length > 1) {
    const lastBreadcrumb =
      store.getters.breadcrumbs[store.getters.breadcrumbs.length - 1];
    await loadData(lastBreadcrumb.id);
    return;
  }

  // 如果没有路由参数也没有保存的状态，获取根目录数据
  await loadData(null);
};
</script>

<style scoped>
.courses-container {
  padding: 10px;
}

.card-list {
  height: calc(90vh - var(--tabbar-height, 50px) - var(--header-height, 70px));
  overflow: auto;
}

.card-wrapper {
  margin-bottom: 15px;
}

.subject-card {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
}

.subject-card:active {
  background-color: #f5f5f5;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-top: 8px;
  color: #999;
  font-size: 13px;
}

.breadcrumb {
  display: flex;
  align-items: center;
  padding: 10px 0;
  flex-wrap: wrap;
}

.breadcrumb-item {
  color: #1989fa;
  cursor: pointer;
}

.breadcrumb-item:hover {
  color: #66b1ff;
}

.separator {
  margin: 0 8px;
  color: #909399;
}

.divider {
  height: 1px;
  width: 100%;
  background-color: #ebedf0;
  margin: 5px 0 15px;
}
</style>
